package cn.lanqiao.common.identifyingCode;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class LowCode
{
  public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  private static Random random = new Random();
  
  public static String generateVerifyCode(int verifySize)
  {
    return generateVerifyCode(verifySize, "23456789ABCDEFGHJKLMNPQRSTUVWXYZ");
  }
  
  public static String generateVerifyCode(int verifySize, String sources)
  {
    if ((sources == null) || (sources.length() == 0)) {
      sources = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    }
    int codesLen = sources.length();
    Random rand = new Random(System.currentTimeMillis());
    StringBuilder verifyCode = new StringBuilder(verifySize);
    for (int i = 0; i < verifySize; i++) {
      verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
    }
    return verifyCode.toString();
  }
  
  public static BufferedImage getBufferedImage(int h, int w, String code)
  {
    BufferedImage img = new BufferedImage(w, h, 1);
    
    Graphics g = img.getGraphics();
    Color c = new Color(236, 240, 255);
    g.setColor(c);
    
    g.fillRect(0, 0, 65, 20);
    
    StringBuilder sb = new StringBuilder();
    char[] ch = code.toCharArray();
    int len = ch.length;
    for (int i = 0; i < len; i++)
    {
      g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
      g.setFont(new Font("Arial", 3, 12));
      g.drawString(String.valueOf(ch[i]), i * 15 + 3, 15);
      sb.append(ch[i]);
    }
    return img;
  }
}
